package com.example.demo.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.example.demo.config.AlipayConfig;
import com.example.demo.entity.Order;
import com.example.demo.service.AlipayService;
import com.example.demo.service.OrderService;
import com.example.demo.service.UserServiceService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@Service
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    private OrderService orderService;
    @Autowired
    private UserServiceService userServiceService;


    public String processPayment(String outTradeNo, String subject, String totalAmount, String body)
            throws IOException, AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(
                AlipayConfig.URL,
                AlipayConfig.APPID,
                AlipayConfig.RSA_PRIVATE_KEY,
                AlipayConfig.FORMAT,
                AlipayConfig.CHARSET,
                AlipayConfig.ALIPAY_PUBLIC_KEY,
                AlipayConfig.SIGNTYPE);

        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url+ outTradeNo);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        System.out.println("[支付宝支付] APPID: " + AlipayConfig.APPID);
        System.out.println("[支付宝支付] notify_url: " + AlipayConfig.notify_url);
        System.out.println("[支付宝支付] return_url: " + AlipayConfig.return_url + outTradeNo);
        System.out.println("[支付宝支付] bizContent: " + body);
        System.out.println("[支付宝支付] FORMAT: " + AlipayConfig.FORMAT);
        System.out.println("[支付宝支付] CHARSET: " + AlipayConfig.CHARSET);
        System.out.println("[支付宝支付] SIGNTYPE: " + AlipayConfig.SIGNTYPE);
        System.out.println("[支付宝支付] GATEWAY: " + AlipayConfig.URL);

        String bizContent = "{" +
                "\"out_trade_no\":\"" + outTradeNo + "\"," +
                "\"total_amount\":\"" + totalAmount + "\"," +
                "\"subject\":\"" + subject + "\"," +
                "\"body\":\"" + body + "\"," +
                "\"product_code\":\"QUICK_WAP_WAY\"" +
                "}";
        System.out.println("[支付宝支付] bizContent: " + bizContent);

        alipayRequest.setBizContent(bizContent);

        // 直接返回完整form字符串
        String payForm = alipayClient.pageExecute(alipayRequest).getBody();
        System.out.println("[支付宝支付] 返回内容：" + payForm);
        return payForm;
    }


    //根据订单号查询支付状态
    public Map<String, Object> queryOrderStatus(String outTradeNo) {
        Map<String, Object> result = new HashMap<>();
        boolean paid = orderService.isOrderPaid(outTradeNo);
        result.put("success", paid);
        result.put("outTradeNo", outTradeNo);
        return result;
    }

    public String handleNotify(Map<String, String> params) {
        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(
                    params,
                    AlipayConfig.ALIPAY_PUBLIC_KEY,
                    AlipayConfig.CHARSET,
                    AlipayConfig.SIGNTYPE);

            if (signVerified) {
                String tradeStatus = params.get("trade_status");
                String outTradeNo = params.get("out_trade_no");

                if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                    orderService.updateOrderStatusByOrderNo(outTradeNo);
                    // 获取订单信息
                    Order order = orderService.getOrder(outTradeNo);
                    int userId = order.getUserId();
                    // 判断服务表是否有该用户
                    if (userServiceService.existsByUserId(userId)) {
                        userServiceService.updateUserService(outTradeNo);
                    } else {
                        userServiceService.createUserService(outTradeNo);
                    }
                }

                return "success";
            } else {
                return "fail";
            }
        } catch (AlipayApiException e) {
            return "fail";
        }
    }
}
